package cn.chiship.framework.business.crawler;

import cn.chiship.framework.business.biz.product.entity.Product;
import cn.chiship.framework.common.util.TrustAllCertManager;
import cn.chiship.sdk.core.base.BaseResult;
import cn.chiship.sdk.core.id.SnowflakeIdUtil;
import cn.chiship.sdk.core.util.JdbcUtil;
import cn.chiship.sdk.core.util.ObjectUtil;
import cn.chiship.sdk.core.util.PrintUtil;
import cn.chiship.sdk.core.util.StringUtil;
import cn.chiship.sdk.core.util.http.HttpUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import java.math.BigDecimal;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/**
 * 义乌小商城商品爬取
 */
public class ChinaGoodCrawler {
    JdbcUtil jdbcUtil = null;

    public void crawlerList(String categoryId, String url) {
        jdbcUtil = new JdbcUtil("com.mysql.cj.jdbc.Driver",
                "jdbc:mysql://localhost:3306/chiship_common_simple?useUnicode=true&characterEncoding=UTF8&useSSL=false&serverTimezone=Asia/Shanghai",
                "root", "123456");
        crawlerList(categoryId, 1, url);
    }

    public void crawlerList(String categoryId, Integer page, String url) {
        System.out.println("正在爬取【" + categoryId + "\t第" + page + "页】数据");
        try {
            TrustManager[] trustManagers = new TrustManager[]{new TrustAllCertManager()};
            SSLContext sslContext = null;
            sslContext = SSLContext.getInstance("SSL");
            sslContext.init(null, trustManagers, new java.security.SecureRandom());
            HttpsURLConnection.setDefaultSSLSocketFactory(sslContext.getSocketFactory());
            Document document = Jsoup.connect(url).get();
            Elements productList = document.getElementsByClass("product_list");
            if (!productList.isEmpty()) {
                Elements productsElement = productList.get(0).select("div.product__item-wrapper");
                for (Element productElement : productsElement) {
                    Product product = new Product();
                    product.setCategoryId(categoryId);
                    String href = "https://www.chinagoods.com" + productElement.select("a").attr("href");
                    String title = productElement.select("a").attr("title");
                    product.setName(title);
                    String image = productElement.select("div.product__img-con").select("img").attr("src");
                    try {
                        image = image.substring(0, image.indexOf("?"));
                    } catch (Exception e) {

                    }
                    product.setSmallImage(image);
                    String price = productElement.select("div.product__info-price").select("span.integer").text() + productElement.select("div.product__info-price").select("span.decimal").text();
                    product.setPrice(BigDecimal.valueOf(Double.parseDouble(price)));
                    product.setCostPrice(BigDecimal.valueOf(Double.parseDouble(price)));
                    crawlerDetail(product, href);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void crawlerDetail(Product product, String url) {
        try {
            TrustManager[] trustManagers = new TrustManager[]{new TrustAllCertManager()};
            SSLContext sslContext = null;
            sslContext = SSLContext.getInstance("SSL");
            sslContext.init(null, trustManagers, new java.security.SecureRandom());
            HttpsURLConnection.setDefaultSSLSocketFactory(sslContext.getSocketFactory());
            Document document = Jsoup.connect(url).get();
            // swiperSlide
            Elements swiperSlides = document.select("div.thums-wp").select("div.banner");
            List<String> largeImages = new ArrayList<>();
            for (Element swiperSlide : swiperSlides) {
                String image = swiperSlide.select("img").attr("src");
                image = image.substring(0, image.lastIndexOf("?"));
                largeImages.add(image);
            }
            product.setLargeImage(StringUtil.join(largeImages, ","));

            //<p style="text-align: center;"><img src="" alt="" data-href="" style=""></p>
            //
            String imageText = "";
            Elements imageElements = document.select("div.p_details_basic_info").select("img");
            for (Element imageElement : imageElements) {
                String image = imageElement.attr("src");
                String alt = imageElement.attr("alt");
                if (!StringUtil.isNullOrEmpty(alt)) {
                    if (!"undefined".equals(alt)) {
                        imageText = imageText + "<p style=\"text-align: center;\"><img src=\"" + image + "\" alt=\"" + alt + "\" data-href=\"" + image + "\" style=\"\"></p>";
                    }
                }

            }
            product.setImageText(imageText);
            String sql = String.format(
                    "INSERT INTO `product`(`id`, `gmt_created`, `gmt_modified`, `is_deleted`,category_id,`name`, `small_image`, `large_image`, `price`, `cost_price`, `is_sale`, `unit`, `total_inventory`,`image_text`) " +
                            "VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?);\n");
            List<Object> params = new ArrayList<>();
            params.add(SnowflakeIdUtil.generateStrId());
            params.add(System.currentTimeMillis());
            params.add(System.currentTimeMillis());
            params.add(Byte.valueOf("0"));
            params.add(product.getCategoryId());
            params.add(product.getName());
            params.add(product.getSmallImage());
            params.add(product.getLargeImage());
            params.add(product.getPrice());
            params.add(product.getCostPrice());
            params.add(Byte.valueOf("1"));
            params.add("件");
            params.add(100000);
            params.add(product.getImageText());
            try {
                jdbcUtil.updateByParams(sql, params);
                System.out.println("成功");
            } catch (SQLException e) {
                e.printStackTrace();
                System.out.println("报错了" + product.getName());
            }

        } catch (Exception e) {
        }
    }

    public static void main(String[] args) {
        ChinaGoodCrawler crawler = new ChinaGoodCrawler();
        crawler.crawlerList(
                "1026754407273324544",
                "https://www.chinagoods.com/search/product/棉柔巾");
    }
}
